<template>
  <div>
    <!-- 面包屑头部导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-alert title="消息提示的文案" type="info" center show-icon :closable="false"></el-alert>

      <!-- 步骤条    -->
      <el-steps :active="activeIndex - 0" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 表单包裹el-tabs可重复使用表单 -->
      <el-form
        label-position="top"
        :model="addGoodsForm"
        :rules="addGoodsRules"
        ref="addGoodsFormRef"
      >
        <!-- 左侧标签 -->
        <el-tabs
          :before-leave="beforeLeave"
          v-model="activeIndex"
          @tab-click="tadsHandleClick"
          tab-position="left"
        >
          <!-- 基本信息tab 表单 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addGoodsForm.goods_price">
                <el-form-item label="商品名称" prop="goods_name">
                  <el-input v-model="addGoodsForm.goods_name"></el-input>
                </el-form-item>
              </el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addGoodsForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addGoodsForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_name">
              <el-cascader
                v-model="cascaderArr"
                :options="cascaderList"
                :props="props"
                @change="addGoodshandleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品参数tab 多选框组 动态参数-->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in manyData" :key="item.attr_id" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(item2,i) in item.attr_vals" :key="i" :label="item2" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品属性tab 静态属性 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in onlyData" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品图片tab 上传  -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              list-type="picture"
              :headers="headersObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>

          <!-- 商品内容tab 富文本 -->
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
            <el-button @click="handleAddGoodsBtn" type="primary" style="margin:10px 0;">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 预览图片  -->
    <el-dialog title="提示" :visible.sync="imgPreviewDialogVisible" width="50%">
      <img style="width:100px" :src="imgUrl" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeIndex: 0,
      addGoodsForm: {
        goods_name: "test",
        goods_price: 10,
        goods_weight: 10,
        goods_number: 10,
        pics: [],
        // 富文本输入内容
        goods_introduce: "",
        // 传给后台的分类id
        goods_cat: "",
        attrs: [
          {
            attr_id: 0,
            attr_value: ""
          }
        ]
      },
      addGoodsRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ]
      },
      cascaderArr: [1, 3, 6],
      cascaderList: [],
      props: {
        //   hover事件触发
        expandTrigger: "hover",
        //   要显示的数据
        label: "cat_name",
        //   要存储传递的数据
        value: "cat_id"
      },
      manyData: [],
      onlyData: [],
      fileList: [],
      headersObj: {
        Authorization: sessionStorage.getItem("token")
      },
      imgPreviewDialogVisible: false,
      imgUrl: ""
    };
  },

  methods: {
    // 切换tab触发
    async tadsHandleClick() {
      if (this.activeIndex == 1) {
        var res = await this.axios.get(
          `categories/${this.cascaderArr[2]}/attributes`,
          {
            params: {
              sel: "many"
            }
          }
        );
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        });
        if (res.meta.status == 200) {
          this.manyData = res.data;
        }
        console.log(this.manyData);
      } else if (this.activeIndex == 2) {
        var res = await this.axios.get(
          `categories/${this.cascaderArr[2]}/attributes`,
          {
            params: {
              sel: "only"
            }
          }
        );

        if (res.meta.status == 200) {
          this.onlyData = res.data;
        }
        console.log(this.onlyData);
      }
    },

    // 获取分类级联信息
    async getCascaderList() {
      var res = await this.axios.get("/categories");
      console.log(res);
      if (res.meta.status == 200) {
        this.cascaderList = res.data;
      }
      console.log(this.cascaderList);
    },

    // 只允许选择3级
    addGoodshandleChange() {
      if (this.cascaderArr.length != 3) {
        return (this.cascaderArr = []);
      }
    },

    // 离开基本信息tab且未选择分类 就不能跳转
    // n是点击的tab o是离开的tab
    beforeLeave(n, o) {
      if (o == 0 && this.cascaderArr.length == 0) {
        this.$mg.error("请选择商品分类");
        return false;
      }
    },

    // 删除图片
    handleRemove(file, fileList) {
      // console.log(file, fileList);
      var filePath = file.response.data.tmp_path;
      var index = this.addGoodsForm.pics.findIndex(item => {
        return item.pic == filePath;
      });
      this.addGoodsForm.pics.splice(index, 1);
      console.log(this.addGoodsForm.pics);
    },

    // 预览图片
    handlePreview(file) {
      console.log(file);
      this.imgPreviewDialogVisible = true;
      this.imgUrl = file.response.data.url;
    },

    // 上传成功才会触发的钩子
    handleSuccess(res) {
      console.log(res);
      if (res.meta.status == 200) {
        this.$mg.success("上传图片成功");
        this.addGoodsForm.pics.push({
          pic: res.data.tmp_path
        });
      }
    },

    // 添加商品按钮
    handleAddGoodsBtn() {
      this.addGoodsForm.goods_cat = this.cascaderArr.join(",");
      console.log(this.manyData);
      this.manyData.forEach(item => {
        this.addGoodsForm.attrs.push({
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(",")
        });
      });
      this.onlyData.forEach(item => {
        this.addGoodsForm.attrs.push({
          attr_id: item.attr_id,
          attr_value: item.attr_vals
        });
      });
      console.log(this.addGoodsForm);
      this.$refs.addGoodsFormRef.validate(async flag => {
        if (!flag) return this.$mg.error("请填写必要的表单");
        var res = await this.axios.post(`goods`, this.addGoodsForm);
        if (res.meta.status == 201) {
          this.$mg.success("添加商品成功");
          this.$router.push("/goods");
        } else {
          this.$mg.error("添加商品失败");
        }
      });
    }
  },

  created() {
    this.getCascaderList();
  }
};
</script>

<style lang='less' scoped>
.el-steps {
  margin-top: 20px;
}
.el-checkbox {
  margin: 5px;
}
</style>
